<?php
/**
 * 同步Lumesse中招发送offer的申请人信息，
 * 发起入职流程
 * 零点之后跑，同步前一天的数据
 * @author dinglin
 */
apf_require_class('Oa_Job_Abstract');
apf_require_class("Bll_Flow_Lumesse");
apf_require_class("Const_Flow");
apf_require_class("Const_User");
apf_require_class("Const_BaseInfo");
apf_require_class('Tools_SendMail');
class Oa_Job_Flow_InputLumesseApplications extends Oa_Job_Abstract {
    private $write_db = "hroa_master";//写数据库
    public function run($params) {
        $this->log("开始同步Lumesse应聘人信息".date('Y-m-d H:i:s'));
        //初始化需要校正的日期,如无指定，取上一天
        $this->date = date('Y-m-d',mktime(0,0,0,date('m'),date('d')-1,date('Y')));
        if ($params) {
            $this->date = date('Y-m-d',strtotime($params));
        }
        $this->_execute_entry_flow();

        $this->log("同步Lumesse部门id处理完".date('Y-m-d H:i:s'));
    }
    private function _execute_entry_flow(){
        $queue = $this->_get_queues();
        $lums_hris_queue = Bll_Flow_Lumesse::get_instance()->Lumesse_HRIS()->Queue();
        $lums_hris_candidate = Bll_Flow_Lumesse::get_instance()->Lumesse_HRIS()->Candidate();
        $lums_hris_document = Bll_Flow_Lumesse::get_instance()->Lumesse_HRIS()->Document();
        $mail_tool = Tools_SendMail::get_instance();
        for($i=0;$i<$queue['count'];$i++){
            $application = $lums_hris_queue->getApplicationFromQueue(array('queueName'=>$queue['status']));
            //if($this->_check_today_applications($application)){ //删除-2013-03-07
            $application = $application->application;
            //入职员工信息
            $candidate = $lums_hris_candidate->getCandidateById(array('candidateId'=>$application->candidateId));
            if($candidate && $candidate->candidate){
                $candidate = $this->_build_candidate($candidate->candidate);
                //获取document offer信息
                $contracts = $lums_hris_candidate->getContractsByApplicationId(array('applicationId'=>$application->id));
                if(isset($contracts->contract)){
                    $contract = $this->_build_contract($contracts->contract);
                    $candidate = array_merge($candidate,$contract);
                }
                //获取document user基本信息
                $offer_feedback_report_id = $this->_get_offer_feedback_report_id($application);

                if($offer_feedback_report_id){
                    $document = $lums_hris_document->getStructuredDocumentById(array('documentId'=>$offer_feedback_report_id));
                    $user_document = $this->_build_user_document($document->structuredDocument);
                    $candidate = array_merge($candidate,$user_document);
                }
                //申请人相关信息
                $user_info = $this->_get_apply_user($application->positionId);
                $candidate = array_merge($candidate,$user_info);
                $candidate['lums_application_id'] = $application->candidateId;//候选人id
                //验证身份证是否重复,如有相同直接移除offer,流入oa成功的发邮件通知对应的HR
                if($this->_check_same_identity_code($candidate['identity_code'])){
                    $this->_start_flow($candidate);
                }else{
                    $mail_tool->send('andycao@anjuke.com','Offer信息流入OA失败提醒','111');
                    exit;
                }
            }
            //}
            $lums_hris_queue->removeApplicationFromQueue(array('queueName'=>$queue['status']));
        }
    }
    /**
     * 检测相同身份证是否存在
     * @param unknown_type $code
     * @return boolean
     */
    private function _check_same_identity_code($code){
        $sql= "select * from entry where identity_code='".$code."'";
        $result = $this->get_db_row($sql,$this->write_db);
        if(empty($result['entry_id'])){
            return true;
        }
        return false;
    }
    private function _build_candidate($candidate){
        $result = array();
        $result['mobile_phone'] = $candidate->address->mobilePhone;
        $result['sex'] = $candidate->personalData->sex->value;
        if($candidate->firstname=="-"){
            $result['user_name']= trim($candidate->lastname);
        }else{
            $result['user_name']= trim($candidate->lastname.$candidate->firstname);
        }
        return $result;
    }
    private function _build_contract($contracts){
        $result = array();
        if(!isset($contracts->type)){
            foreach($contracts as $con){
                $contract = $con;
                break;
            }
        }else{
            $contract = $contracts;
        }
        $result['lums_user_type'] = $contract->type;
        $result['plan_start_date'] = $contract->plannedStartDate;
        foreach($contract->freeFormFields->freeFormField as $field){
            if($field->value == 'Grade'){
                $result['p_m_level'] = $field->_;
            }elseif($field->value == 'Work Location'){
                $result['work_space'] = $field->_;
            }
            elseif($field->value == 'Probation ending date'){
                $result['probation_end_date'] = $field->_;
            }
            elseif($field->value == 'Sign off city'){
                $result['sign_off_city'] = $field->_;
            }
        }
        return $result;
    }
    private function _build_user_document($document){
        $result = array();
        foreach($document->answers->answer as $answer){
            if($answer->assignedQuestion->unlocalValue == '紧急联络人'){
                $result['urgent_person'] = $answer->freeText;
            }elseif($answer->assignedQuestion->unlocalValue == '身份证号码'){
                $result['identity_code'] = $answer->freeText;
            }elseif($answer->assignedQuestion->unlocalValue == '通讯地址'){
                $result['call_space'] = $answer->freeText;
            }elseif($answer->assignedQuestion->unlocalValue == '紧急联络人联系方式'){
                $result['urgent_phone'] = $answer->freeText;
            }
        }
        return $result;
    }
    /**
     * 获取 Offer Feedback Report的document的ID
     */
    private function _get_offer_feedback_report_id($application){
        $id = 0;
        foreach($application->documents->document as $document){
            if($document->name == 'Offer Feedback Report'){
                $id = $document->id;
            }
        }
        return $id;
    }
    private $old_flow_id=0;
    /**
     * 获取职位申请人信息
     */
    private function _get_apply_user($lums_positon_id){
        $result = array();
        $sql = "SELECT user_id,job_id,user_type,work_city_id,flow_id FROM apply_recruit WHERE lums_position_id=".$lums_positon_id;
        $result = $this->get_db_row($sql,$this->write_db);
        if($result){
            $result['parent_id'] = $result['user_id'];
        }else{
            $result['parent_id'] = 0;
        }
        $this->old_flow_id = $result['flow_id'];//创建新员工档案为了绑定一个添加人，到时好修改
        unset($result['flow_id']);
        $sql = "SELECT job_id FROM work WHERE user_id=".$result['user_id']." AND is_parttime=1 AND is_deleted=1";
        $result2 = $this->get_db_row($sql,$this->write_db);
        if($result2){
            $result['parent_job_id'] = $result2['job_id'];
        }else{
            $result['parent_job_id'] = 0;
        }
        return $result;
    }
    /**
     * 检查确认录用时间
     */
    private function _check_today_applications($application){
        $boolean = false;
        if($application){
            $app = $application->application ;
            foreach($app->applicationHistory->applicationFollowup as $flow){
                $_date = date('Y-m-d',strtotime($flow->updateDate));
                if($flow->applicationStatus == "Hired" && $_date == $this->date){
                    $boolean = true;
                }
                echo $flow->applicationStatus;
            }
        }
        return $boolean;
    }
    /**
     * 获取队列
     */
    private function _get_queues(){
        $applications = array();
        $lums_hris_queue = Bll_Flow_Lumesse::get_instance()->Lumesse_HRIS()->Queue();
        $queues = $lums_hris_queue->listAllQueuesDetailed();
        $status ='';
        $elementsCount = 0;
        if($queues && $queues->queues && $queues->queues->queue){
            foreach ($queues->queues->queue as $queue){
                if($queue->name == 'New Hires'){
                    $status = $queue->name;
                    $elementsCount = $queue->elementsCount;
                }
            }
        }else{
            return $applications;
        }
        return array('status'=>$status,'count'=>$elementsCount);
    }
    /**
     * 入职流程
     */
    private function _start_flow($candidate){

        $data = $this->_build_lumesse_data($candidate);
        $data['entry']['user_code'] = "'".$this->_get_bll_hroa()->get_user_code($data['entry']['user_type'], $data['entry']['city_id'],false)."'";
        //入职表
        $entry_id = $this->_insert('entry',$data['entry']);
        $data['extend']['entry_id'] = $entry_id;
        //拓展表
        $this->_insert('entry_extend', $data['extend']);
        //添加代办事项
        $data_flow = $this->_build_flow_info($entry_id,$data);
        $flow_id = $this->_insert('flow',$data_flow);
        //记录到log
        $data_log = $this->_build_operate_log($flow_id,$entry_id,$data);
        $this->_insert('operate_log',$data_log);
    }
    private function _insert($table,$entry){
        $sql = "INSERT INTO ".$table."(".join(',',array_keys($entry)).") VALUES(".join(',',$entry).")";
        return $this->execute($sql,array(),$this->write_db);
    }
    /**
     * 有字段需要创建
     */

    private function _build_lumesse_data($candidate){
        $result = array();
        //$user_types = Const_User::get_lumesse_to_hroa_user_type();
        $result['entry']['real_name'] = "'".$candidate['user_name']."'";
        if($candidate['sex'] == 'F'){
            $result['entry']['sex'] = 2;
        }elseif($candidate['sex'] == 'M'){
            $result['entry']['sex'] = 1;
        }
        $result['entry']['cellphone'] = "'".$candidate['mobile_phone']."'";
        $result['entry']['identity_type'] = 1;
        $result['entry']['identity_code'] ="'".$candidate['identity_code']."'";
        $result['entry']['entry_date'] = intval(date('Ymd',strtotime($candidate['plan_start_date'])));
        $result['entry']['re_entry_date'] = $result['entry']['entry_date'];
        $city_id = $this->_get_sign_city($candidate['sign_off_city']);
        $result['entry']['city_id'] = $city_id;
        $result['entry']['work_city_id'] = $candidate['work_city_id'];
        $result['entry']['user_type'] = $candidate['user_type'];//$user_types[$candidate['user_type']];
        $result['entry']['job_id'] = $candidate['job_id'];
        $result['entry']['parent_id'] = $candidate['parent_id'];
        $result['entry']['parent_job_id'] = $candidate['parent_job_id'];

        $result['extend']['present_address'] = "'".$candidate['call_space']."'";//通讯地址
        $result['extend']['emergency_people'] = "'".$candidate['urgent_person']."'";//紧急联系人
        $result['extend']['emergency_phone'] = "'".$candidate['urgent_phone']."'";//紧急联系人联系方式
        $level_p_m = $this->_get_p_m_level($candidate['p_m_level']);
        $result['extend']['p_level'] = $level_p_m['p_level_id']; //职级
        $result['extend']['m_level'] = $level_p_m['m_level_id']; //职级
        $result['extend']['trial_start'] = intval(date('Ymd',strtotime($candidate['plan_start_date'])));//适用期，开始，时间
        $tmp_date = explode("/",$candidate['probation_end_date']);
        if(count($tmp_date)==3){
            $candidate['probation_end_date'] = intval($tmp_date[2].$tmp_date[1].$tmp_date[0]);
        }else{
            $candidate['probation_end_date'] = intval(date('Ymd',strtotime($candidate['probation_end_date'])));
        }
        $result['extend']['trial_end'] = $candidate['probation_end_date'];//适用期，结束，时间
        $result['extend']['lums_application_id'] = $candidate['lums_application_id'];
        return $result;
    }
    private function _get_birth_day_from_identity_code($code){
        $birth = 0;
        if(strlen($code)=='18'){
            $birth = intval(substr($code, 6,8));
        }
        return $birth;
    }
    private function _get_sign_city($city_name){
        $city_list = Const_BaseInfo::get_city_list();
        $city_name = strtolower($city_name);
        $city_id = 11;
        foreach ($city_list as $city){
            if($city['pinyin'] == $city_name){
                $city_id = $city['city_id'];
                break;
            }
        }
        return $city_id;
    }
    private function _get_p_m_level($p_m_level){
        $p_m_level = strtoupper($p_m_level);
        $p_levels = Const_User::get_p_degree();
        $m_levels = Const_User::get_m_degree();

        $m_level_id = 0;
        $p_level_id = 0;
        foreach($p_levels as $p){
            if($p['degree'] == $p_m_level){
                $p_level_id = $p['id'];
                break;
            }
        }
        foreach($m_levels as $m){
            if($m['degree'] == $p_m_level){
                $m_level_id = $m['id'];
                break;
            }
        }
        return array('p_level_id'=>$p_level_id,'m_level_id'=>$m_level_id);
    }
    /**
     * 构建日志数据
     * @return array()
     */
    private function _build_operate_log($flow_id,$entry_id,$data){
        //操作人取同步职位到lumesse中的人员
        $sql = "SELECT * FROM operate_log where flow_id={$this->old_flow_id} AND flow_stage=".Const_Flow::FLOW_RECRUIT_14;
        $opt_log = $this->get_db_row($sql,$this->write_db);
        $opt_user_id= 0;
        if(!empty($opt_log['opt_user_id'])){
            $opt_user_id = $opt_log['opt_user_id'];
        }
        $result = array(
                'flow_stage'=>intval(Const_Flow::FLOW_ENTRY_1),//第一阶段，档案录入
                'flow_type'=>intval(Const_Flow::FLOW_TYPE_ENTRY),//入职流程
                'flow_opt'=>intval(Const_Flow::PHASE_1),//入职-新建员工档案
                'user_id' =>intval($entry_id),
                'opt_user_id'=>$opt_user_id,//操作人id
                'role_type'=>intval(Const_Flow::ROLE_RECRUIT),//行政招聘
                'work_city_id'=>intval($data['entry']['work_city_id']),
                'flow_id'=>intval($flow_id),
                'user_name'=>$data['entry']['real_name'],
                'effect_date'=>$data['entry']['entry_date']
        );
        //发送邮件通知相应HR，offer流入成功
        if($opt_user_id){
            $sql = "select user_id,office_mail from user where user_id=".$opt_user_id;
            $user = $this->get_db_row($sql,$this->write_db);
            $mail_tool = Tools_SendMail::get_instance();
            $mailcontent = $data['entry']['real_name']."创建新员工档案于".date('Y-m-d')."<br><a href='http://home.corp.anjuke.com/flow/?do=process'>流程查看</a>";
            $mail_tool->send($user['office_mail'],$data['entry']['real_name'].'Offer信息流入OA提醒',$mailcontent);
        }
        return $result;
    }
    /**
     * 构建待办事项数据
     * @param array $data
     */
    private function _build_flow_info($entry_id,$data){
        $result = array(
                'user_id'=>$entry_id,
                'user_name'=>$data['entry']['real_name'],
                'flow_type'=>Const_Flow::FLOW_TYPE_ENTRY,//入职流程
                'flow_stage'=>Const_Flow::FLOW_ENTRY_1,//第一阶段，档案录入(now)
                'flow_opt'=>Const_Flow::PHASE_1,//入职-新建员工档案(now)
                'flow_role_list'=>"'".Const_Flow::ROLE_ADMIN.','.Const_Flow::ROLE_IT."'",//下一步，行政管理,IT管理(next)
                'work_city_id'=>$data['entry']['work_city_id'],
                'effect_date'=>$data['entry']['entry_date'],
                'now_status'=>Const_Flow::FLOW_STATUS_DOING,//事项开始进行(now)
        );
        return $result;
    }
    /**
     * hroa interface bll
     * @return Bll_Hr_Property
     */
    private function _get_bll_hroa(){
        if(!$this->bll_hroa ){
            apf_require_class('Bll_Hr_OutInterface');
            $this->bll_hroa = new Bll_Hr_OutInterface();
        }
        return $this->bll_hroa;
    }
}